package com.smart.platform.Filter;

import com.alibaba.fastjson.JSON;
import com.smart.platform.common.BaseContext;
import com.smart.platform.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//检查我们用户是否已经完成了登录，这是一个过滤器
@Slf4j
//这里是定义了我们过滤器的名称以及拦截路径/*代表全部拦截
//@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
//要使用过滤器就需要继承这个Filter这个接口
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    //登录校验逻辑代码 （基于session）
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到了本次请求：{}", request.getRequestURI());

        //定义一个字符串数组 存放那些不需要拦截的路径
        String[] urls = new String[]{
                "/Teachers/login",
                "/Teachers/logout",
                "/Teachers/save",
                "/Students/login",
                "/Students/logout",
                "/Students/save",
                "/doc.html",
                "/swagger-resources",
                "/v2/api-docs"
        };

        /*  String[] urls = new String[]{
                "/Teachers/**",
                "/Teachers/login",
                "/Teachers/logout",
                "/Students/**",
                "/Students/login",
                "/Students/logout",
                "/common/**",
                "/text/**",
                "/upload/**",
                "/respond/**",
                "/analysis/**"
        };*/

        //2.判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3.如果不需要处理，则直接放行
        if (check) {
            log.info("本次请求不需要处理：{}", request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }

        //4.判断登录状态，如果已经登录，则直接放行
        if (request.getSession().getAttribute("userId") != null) {
            String userId = (String) request.getSession().getAttribute("userId");
            log.info("用户已登录，用户userId为：{}", userId);
            //获取当前用户id用于设置公共字段
            //给当前线程设置 id值 然后再执行放行方法
            BaseContext.setCurrentUserId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        //5.如果未登录 则返回标准格式的未登录结果 或者是 登录的信息错误这个在controller层处理了
        log.info("未登录");
        response.getWriter().write(JSON.toJSONString(Result.error("NOT LOGIN")));
    }

    /**
     * 路径匹配方法，检查本次请求路径是否可以直接放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls, String requestURI) {
        // 遍历urls数组中的每一个url
        for (String url : urls) {
            // 使用PATH_MATCHER对requestURI和url进行匹配，如果匹配成功，返回true
            boolean match = PATH_MATCHER.match(url, requestURI);
            // 如果匹配成功，返回true
            if (match) {
                return true;
            }
        }
        // 如果遍历完urls数组，没有匹配成功的，返回false
        return false;
    }


}
